﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace cpk_dec
{
    class BitWriter:BinaryWriter
    {
        byte bit_pool;
        int bit_move_count;
        public BitWriter(Stream input)
            : base(input)
        {
            bit_move_count = 8;
            bit_pool = 0;
        }
        public override void Flush()
        {
            bit_pool <<= bit_move_count;
            base.Write(bit_pool);
            base.Flush();
        }
        public override void Close()
        {
            this.Flush();
            base.Close();
        }

        private void putbits(byte param, int bcnt)
        {
            int b1 = bit_move_count - bcnt;
            if (bcnt > 8)
                throw new Exception("Too many bits");
            if (b1 > 0)
            {
                bit_pool <<= bcnt;
                bit_move_count -= bcnt;
                bit_pool |= (byte)(param & ((1 << bcnt) - 1));
            }
            else
            {
                int p1 = -b1;
                int p2 = bit_move_count;
                bit_pool <<= p2;
                bit_pool |= (byte)((param >> p1) & (1 << p2 - 1));
                base.Write(bit_pool);
                bit_pool = (byte)(param & (1 << p1 - 1));
                bit_move_count = 8 - p1;
            }
        }
        public void WriteBit(int param, int bcnt)
        {
            byte[] buf=new byte[(bcnt-1)/8+1];
            int i=0;
            while (param > 0 || i==0)
            {
                buf[i++] = (byte)(param & 0xff);
                param >>= 8;
            }
            int p1 = (bcnt-1) % 8 + 1;
            putbits(buf[--i], p1);
            while (i>0)
            {
                i--;
                putbits(buf[i], 8);
            }
        }




    }
}
